<?php

class LocationController extends Zend_Controller_Action
{
    public function init()
    {
		$auth = Zend_Auth::getInstance();

		if ( !$auth->hasIdentity() ) $this->_redirect('/auth');

		$this->usr = $this->view->usr = $auth->getIdentity();

		$this->db 	= Zend_Registry::get('db');
    }

    public function indexAction()
    {
    	if ( $this->getRequest()->isPost() ){
	    	$address = urlencode( $this->_getParam('city') ).",+".urlencode( $this->_getParam('ctry') );

	    	$xml 	= file_get_contents("http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=false");
	    	$rspn 	= simplexml_load_string($xml);

	    	if ( $rspn->status == 'OK' ){
	    		$City 	= $rspn->xpath("/GeocodeResponse/result/address_component[type='locality']/long_name");
	    		$Ctry 	= $rspn->xpath("/GeocodeResponse/result/address_component[type='country']/long_name");

	    		$Lat 	= $rspn->xpath("/GeocodeResponse/result/geometry/location/lat");
	    		$Lng 	= $rspn->xpath("/GeocodeResponse/result/geometry/location/lng");


				$Lctns_Id = $this->db->fetchOne("
									SELECT
										Id
									FROM
										Lctns
									WHERE
										Lat = ? AND Lng = ?
									", array( $Lat[0], $Lng[0] ) );

				if ( !$Lctns_Id ){

					if ( !$City[0] ) $City[0] = 'Unknown';

		    		$data = array(
		    						'Locality' 	=> $City[0],
		    						'Country' 	=> $Ctry[0],
		    						'Lat' 		=> $Lat[0],
		    						'Lng' 		=> $Lng[0]
		    					);

					$this->db->insert( 'Lctns', $data);

					$Lctns_Id = $this->db->lastInsertId();
				}

				setcookie('LL', $Lctns_Id );

	    	}else{

	    		// Log error
	    	}

	    	exit;
    	}
    }
}